package cn.szzsi.business.controller.admin;

import cn.szzsi.AConfig;

import cn.szzsi.business.interceptor.OperationLogsInterceptor;
import cn.szzsi.business.service.CompanyInfoService;

import cn.szzsi.common.bean.dto.Msg;

import cn.szzsi.common.util.ChineseToEnglish;
import cn.szzsi.common.util.CommonUtil;

import cn.szzsi.common.util.StringUtils;

import cn.szzsi.core.dubbo.CardDubboService;

import cn.szzsi.core.dubbo.DubboService;
import cn.szzsi.dto.WeChatThirdPlateformDto;
import cn.szzsi.mallservice.ApiInterface;
import cn.szzsi.model.*;

import cn.szzsi.service.WeChatConfigInterface;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.*;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.redis.Redis;
import org.apache.commons.codec.digest.DigestUtils;


import javax.servlet.http.Cookie;
import java.util.*;

/**
 * 后台类 - 后台管理、管理员
 */
public class AdminController extends Controller {

    private Admin admin;
    private Member member;


    // 登录页面
    @Clear
    public void index() {
        setAttr("base", getRequest().getContextPath());
        render(CommonUtil.TEMPLATE_PATH + "/business/admin/admin_login.html");
    }
    // 登录验证
    @Clear
    @Before(OperationLogsInterceptor.class)
    public void singIn() {
        String username = getPara("username", "");
        String password = getPara("password", "");
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            renderJson(Msg.fail("账号和密码不能为空!", ""));
            return;
        }

        Member loginMember = Member.dao.getBusinessByAll(username);//商户
        if (loginMember != null) {//商户
            //查看商户是否被禁用
            CompanyInfo companyInfo=CompanyInfo.dao.getByShopId(loginMember.getId());
            if("1".equals(companyInfo.getIsDisable())){
                renderJson(Msg.fail("该用户已被禁用,请联系管理员!", ""));
                return;
            }
            if (!Member.dao.verifyMember(loginMember, password)) {//密码错误
                renderJson(Msg.fail("您的用户名或密码错误!", ""));
                return;
            }

            loginMember.set("loginIp", getRequest().getRemoteAddr());
            loginMember.set("loginDate", new Date());
            loginMember.update();

            // 写入会员登录名Cookie和登录类型Cookie
            Cookie loginMemberUsernameCookie=new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME,loginMember.getUsername().toLowerCase());
            Cookie loginTypeCookie=new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "business");//登录类型
            loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
            loginTypeCookie.setPath(getRequest().getContextPath() + "/");
            setCookie(loginMemberUsernameCookie);
            setCookie(loginTypeCookie);

            //写入会员登陆_auth(可以凭借_auth换取用户信息)
            String _auth=StrKit.getRandomUUID();
            Cookie authCookie = new Cookie("_auth",_auth);//登录类型
            authCookie.setPath(getRequest().getContextPath()+"/");
            setCookie(authCookie);

            //将上一步的auth存入Redis缓存服务器
            Map map=new HashMap();
            map.put("b_shoprank",loginMember.getBShoprank());
            map.put("id",loginMember.getId());
            map.put("username",loginMember.getUsername());
            Redis.use("zshop").setex(_auth,3600,JsonKit.toJson(map));

            //将商户名写入Cookie(可以根据username获取商户自定义后台登陆界面)
            Cookie shopAliasCookie =new Cookie("username",loginMember.getUsername());
            shopAliasCookie.setPath(getRequest().getContextPath()+"/");
            setCookie(shopAliasCookie);

            renderJson(Msg.SUCCESS);
        } else {
            renderJson(Msg.fail("对不起,该用户不存在!", ""));
        }
    }


    @Clear
    public void register(){
        render(CommonUtil.TEMPLATE_PATH + "/business/admin/register.html");
    }

    @Clear
    @Before(Tx.class)
    public void registerIn(){
        member = getModel(Member.class);
        String phone = getPara("phone");//联系电话
        String captcha=getPara("captcha");//验证码
        String username = getPara("username");//用户名
        String password = getPara("password");//密码


        if(CacheKit.get("sms",phone)==null){
            renderJson(Ret.fail("info","手机验证码已过期,请重新获取"));
            return;
        }
        if(!captcha.equals(CacheKit.get("sms",phone).toString())){
            renderJson(Ret.fail("info","手机验证码错误"));
            return;
        }
        if(Member.dao.getBusinessByUsername(username)!=null){
            renderJson(Ret.fail("info","注册失败,商户已存在"));
            return;
        }
        member.set("id", CommonUtil.getUUID());
        member.set("username", username);
        member.set("password", DigestUtils.md5Hex(password));
        //member.set("brandName", brandName);
        //member.set("categories",categories);
        member.set("shopId", "0");
        member.set("createDate", new Date());
        member.set("deposit", 0);
        member.set("roleId", "super");
        member.set("b_shoprank", "super");
        member.set("isAccountEnabled", 1);
        member.set("isAccountLocked", 0);
        member.set("loginFailureCount", 0);
        member.set("point", 0);
        member.set("registerIp", "");
        member.save();

        /**
         * 企业相关信息保存
         */
        String brandName=getPara("brandName");//品牌商名称
        String personInCharge=getPara("personInCharge");//企业负责人
        String categories=getPara("categories");//所属行业

        CompanyInfoService.cis.saveInfo(phone,brandName,personInCharge,categories,"0",member.getId());

        /**
         * 商城配置信息
         */
        try {
            JSONObject backJson=DubboService.getInstance().imports(ApiInterface.class).updateSiteConfig(ChineseToEnglish.getPingYin(brandName),member.getId());
            if(backJson.getInteger("code")!=0){
                renderJson(Ret.fail("info","保存失败!"));
                return;
            }
        }catch (Exception e){
            System.out.println("注册商城失败-----------------"+e.getMessage());
        }

        //写入会员登陆_auth(可以凭借_auth换取用户信息)
        String _auth=StrKit.getRandomUUID();
        Cookie authCookie = new Cookie("_auth",_auth);//登录类型
        authCookie.setPath(getRequest().getContextPath()+"/");
        setCookie(authCookie);

        //将上一步的auth存入Redis缓存服务器
        Map map=new HashMap();
        map.put("b_shoprank",member.getBShoprank());
        map.put("id",member.getId());
        map.put("username",member.getUsername());
        Redis.use("zshop").setex(_auth,3600,JsonKit.toJson(map));

        //保存微信系统相关信息
        try {
            WeChatConfigInterface weChatConfigInterface= CardDubboService.getInstance().imports(WeChatConfigInterface.class);
            WeChatThirdPlateformDto weChatThirdPlateformDto =weChatConfigInterface.viewThirdPlateformConfig("1");//查询第三方平台配置信息
            if(weChatThirdPlateformDto!=null){
                String thirdAppId=weChatThirdPlateformDto.getThirdAppId();
                weChatConfigInterface.saveWeChatSiteConfig(member.getId(),thirdAppId);
            }
        }catch (Exception io){
            System.out.println("----------------保存WesiteConfig失败!");
        }

        renderJson(Ret.ok("info","保存成功!").set("shopId",member.getId()));
    }

    /**
     * 注册成功后跳转的页面
     */
    public void afterRegister(){
        render(CommonUtil.TEMPLATE_PATH + "/business/admin/register_success.html");
    }


    @Clear
    /**
     * 获取短信验证码
     */
    public void getCaptcha(){
        String phone=getPara("phone");
        CompanyInfo companyInfo=CompanyInfo.dao.getByPhone(phone);
        if(companyInfo!=null){
            renderJson(Ret.fail("info","该手机号已经注册,请换个试试!"));
            return;
        }
        String captcha = CommonUtil.getSixRandom();//六位纯数字验证码
        PlateformConfig plateformConfig=PlateformConfig.dao.findById(1);
        String sms_signature=plateformConfig.getSmsSignature();
        String message = "【"+sms_signature+"】验证码"+captcha+" ，请勿将验证码告知他人。";
        Map map=new HashMap();
        map.put("shopId","0");
        map.put("phone",phone);
        map.put("content",message);
        map.put("sms_type","yzm");
        map.put("app_key","zshop");
        map.put("captcha",captcha);
        String reqUrl= AConfig.p.get("sms")+"/sms/send";//短信服务器接口;
        String result= HttpKit.get(reqUrl,map);
        JSONObject obj= JSON.parseObject(result);
        if("0".equals(obj.get("code").toString())){
            renderJson(Ret.ok("info","发送成功"));
            CacheKit.put("sms",phone,captcha);
            System.out.println("captcha-------------"+captcha);
        }else{
            renderJson(Ret.fail("info",obj.get("desc")));
        }
    }


}
